<?php
class UserModel extends Model{
 
	function init(){
		$this->OpenDB();
	}

	function getList($page=null,$limit=null){ 
		settype($page, 'integer');
		settype($limit, 'integer');
		$sql="select * from @#__user order by user_id desc";
		$count=$this->db->num_rows($this->db->query($sql));
		if($limit){
			if ($page){
				if($page>ceil($count/$limit))
				$page=$count/$limit;
				elseif ($page<1) {
					$page=1;
				}
				$start=$page*$limit-$limit;
				if ($start<0)$start=0;
			} 
			else 
			$start=0;
			$sql.=" limit $start,$limit";
		} 
		$rt['data']=$this->db->fetchRows($sql);
		$rt['count']=$count;
		$rt['pagecount']=ceil($count/$limit);
		return $rt; 
	}
	
	/**
	 * 判断用户是否登录
	 * @param boolean $status 如果未登录是否跳转到登录页面 default false
	 */
	static public function isLogin($status=false){
		global $_SID;
	 	//header("location:".PATH."/index.php/login");
	 	$user=getInf('USER_NAME');
	 	$type=getInf('USER_TYPE');
	 	$logtime=getInf('LOGIN_TIME');
	 	
	 	if (!$user || !$type){
	 		if ($status){header("location:".PATH."/index.php/Login?$_SID=".getSid()."&returl=".enUrl(getUrl()));}
	 		return false;
	 	};
	 	return true;
	}
	/**
	 * 用户登录
	 * @param string $user
	 * @param string $pass
	 */
	public  function Login($user,$pass){
		$user = qstr($user);
		$pass = qstr($pass);
		$return='';
		$sql="select * from @#__user where user_name='$user'";
		$rs=$this->db->get_one($sql);
		if ($rs){
			if (md5($pass)!=$rs['user_pass']){
				return '密码错误';
			} 
			if ($rs['user_status']=='0'){
				return '账号被锁定';
			}  
			$_SESSION['TK_USER']['LOGIN_TIME']=empty($rs['user_logtime'])?time():$rs['user_logtime'];
			$_SESSION['TK_USER']['USER_NAME']=$user;
			$_SESSION['TK_USER']['USER_ID']=$rs['user_id'];
			$_SESSION['TK_USER']['USER_TYPE']=$rs['user_type'];
			$sqll="update @#__user set user_logtime=".time();
			if (empty($rs['user_regtime']))$sqll.=",user_regtime=".time();
			$where=" where user_id=".$rs['user_id'];
			$sqll.=$where;
			$this->db->query($sqll);
			
			if (isset($_SERVER['HTTP_IMEI'])){
				$imei=$_SERVER['HTTP_IMEI'];
				$sql="UPDATE @#__mao set mao_imei='$imei' where mao_user=".$rs['user_id'];
				@$this->db->query($sql);
			}
			return "登录成功";
		}else{
			return "用户名不正确";
		}
	}
	/**
	 * 注册用户
	 * @param string $username
	 * @param string $usernick
	 * @param string $userpass
	 * @param string $phone
	 * @param int $sex
	 * @param string $usermobile
	 */
	public function Register($username,$usernick,$userpass,$email,$phone='135',$sex=1,$usermobile='ME'){
		$username = qstr($username);
		$usernick = qstr($usernick);
		$userpass = qstr($userpass);
		$email = qstr($email);
		$phone = qstr($phone);
		$usermobile = qstr($usermobile);
		settype($sex, 'integer');
		
		$sql="select * from @#__user where user_name='$username' or user_email='$email' or user_phone=$phone or user_nick='$usernick'"; 
		@$query=$this->db->query($sql) or new appException("注册失败");
		if (($row=$this->db->fetch_array($query))){
			if ($row['user_name']==$username)return "用户名 $username 已存在";
			if ($row['user_nick']==$usernick)return "昵称 $usernick 已被使用";
			if ($row['user_phone']==$phone)return "手机号码 $phone 已被使用";
			if ($row['user_email']==$email)return "邮件地址$email 已被使用";
		}else{	
				$userpass=md5($userpass);		
				if ($this->db->query("INSERT INTO @#__user(user_name,user_pass,user_nick,user_sex,user_phone,user_email,user_mobile,user_regtime)VALUES
			('$username','$userpass','$usernick',$sex,$phone,'$email','$usermobile',UNIX_TIMESTAMP())"))return 'OK';
		}
		return 'NO';
	}
	
	public function Update($username,$usernick,$userpass,$phone='135',$sex=1,$usermobile='ME',$userhead=null,$userid=null){
		$username = qstr($username);
		$usernick = qstr($usernick);
		$userpass = qstr($userpass);
		$phone = qstr($phone);
		$usermobile = qstr($usermobile);
		if($userhead)$userhead = qstr($userhead);
		if($userid)settype($userhead, 'integer');
		settype($sex, 'integer');
		
		$sql="select * from @#__user where (user_name='$username'  or user_phone=$phone or user_nick='$usernick' )";
		$sql.="and user_id<>$userid";
	 	$query=$this->db->query($sql);
		if (($row=$this->db->fetch_array($query))){
			if ($row['user_name']==$username)return "用户名 $username 已存在";
			if ($row['user_nick']==$usernick)return "昵称 $usernick 已被使用";
			if ($row['user_phone']==$phone)return "手机号码 $phone 已被使用";
		}else{
			if (empty($userid)){ 
				return "修改的会员不存在";
			}else{ 
				if ($this->db->query("UPDATE @#__user SET user_pass='$userpass',user_nick='$usernick',user_sex=$sex,user_phone=$phone,user_mobile='$usermobile' where user_id=$userid"))return 'OK';
			}
		}
		return 'NO';
	}
	
	public function SmsReg($user,$nick,$pass,$phone,$mail,$sex,$tjid){
		$user = qstr($user);
		$nick = qstr($nick);
		$phone = qstr($phone);
		$mail = qstr($mail);
		$sex = qstr($sex);
		$tjid = qstr($tjid);
		
		settype($tjid, 'integer');
		
		$sql="SELECT * FROM @#__user WHERE user_name='$user'";
		$query=$this->db->get_one($sql);
		if($query){
			$enpass=md5($pass);
			$sql="UPDATE @#__user SET user_pass='$enpass' where user_id={$query['user_id']}";
			$this->db->query($sql);
			return 11;
		}else{
			$enpass=md5($pass);
			$sql="INSERT INTO @#__user(user_name,user_pass,user_nick,user_sex,user_phone,user_email,user_mobile,user_regtime)VALUES
			('$user','$enpass','$nick',$sex,$phone,'$mail','未设置',UNIX_TIMESTAMP())";
			$rt = $this->db->query($sql);
			if($rt){
				//赠送金币给新注册用户
				$gift_money = SiteConfig::get('gift_money');
				if($gift_money > 0){
					$user_id = $this->db->insert_id();
					$this->moneyManager($user_id, 1, $gift_money);
				}
			}
			return  1;
		}
	}
	
	public function DelUser($id){
		settype($id, 'integer');
        $sql = "SELECT user_name FROM @#__user WHERE user_id='$id'";
        $query = $this->db->get_one($sql);
        if(!$query){
            return '用户不存在!';
        }
        $this->db->query("DELETE FROM @#__user WHERE user_id='$id'");
		return $query['user_name'].'删除成功';
	}
	
	public function getInfo($userid){
		settype($userid, 'integer');
		$sql="select * from @#__user where user_id=$userid";
		$row=$this->db->get_one($sql);
		return $row;
	}
	
	public static function Logout(){
		unset($_SESSION['TK_USER']);
	}

    /**
     * 用户金币操作
     * @param int $userId 用户ID
     * @param int $optionType 操作类型
     * @param int $number 操作数量
     * @return boolean
     */
    public function moneyManager($userId, $optionType , $number){
    	settype($userId, 'integer');
        $optionType = ($optionType == 1 ? '+' : '-');
        $sql = 'UPDATE @#__user SET user_money=user_money'.$optionType.$number.' WHERE user_id='.qstr($userId);
        return (boolean)$this->db->query($sql);
    }
}